package myJs.user.data

import cats.effect.SyncIO
import japgolly.scalajs.react._
import japgolly.scalajs.react.component.Scala.BackendScope
import japgolly.scalajs.react.vdom.HtmlTags
import myJs.Implicits._
import myJs.Utils._

import scala.scalajs.js.Dynamic.{global => g}
import myJs.myPkg._
import myJs.myPkg.bootstrap.Bootstrap.default._
import myJs.myPkg.jquery._
import myJs.tool.Pojo.FilterContentData
import myJs.tool.Tool
import myJs.tool.Tool._
import org.scalajs.dom._
import org.scalajs.dom.ext.Ajax
import shared.VarTool

import scala.collection.SeqMap
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._

import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.{Date, JSON}
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import myJs.myPkg.Vue._

import js.Dynamic.literal
import japgolly.scalajs.react.vdom.all._

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("DataDetail")
object DataDetail {
  val tableId = "table"

  @JSExport("init")
  def init = {
    viewShow(getId)

    //    test

  }

  val currentValue: Option[String] = None

  def eventTest(e: ReactEventFromInput) = {
    currentValue.map { before =>
      val after = e.target.value
      val v = s"from ${before} to ${after}"
      val options = SwalOptions(
        `type` = "success",
        title = messages("success"),
        text =v
      )
      Swal.swal(options)
      SyncIO{}
    }
  }

  def test = {

    case class MyValue(v: String)
    class InputComponent(bs: BackendScope[Unit, MyValue]) {
      def render(s: MyValue) = {
        input(onChange ==> myOnChange, value := s"${s.v}")
      }

      def myOnChange(e: ReactEventFromInput) = {
        val newValue = e.target.value
        bs.modState(_.copy(v = newValue))
      }

      def tick = {
        bs.modState(s => MyValue(new Date().toLocaleTimeString()))
      }

      def start = SyncIO {
        js.timers.setInterval(1000)(tick.unsafeRunSync())
        ()
      }

    }

    val inputComponent = ScalaComponent.builder[Unit].initialState(MyValue("yz")).renderBackend[InputComponent].
      componentDidMount(_.backend.start).
      build

    val names = List("Alice")
    val opStr: Option[String] = Some("yz")
    val opHtml = opStr.whenDefined { str =>
      TagMod(div(str))
    }
    val hasFocus = false
    val customAttr = VdomAttr("customAttr")
    val customStyle = VdomStyle("customStyle")
    val customHtmlTag = HtmlTag("customTag")
    //    val html = names.toReactFragment { name =>
    //      div(
    //        inputComponent(
    //          //        onChange ==>? eventTest,
    //        ),
    //        inputComponent(),
    //        inputComponent()
    //      )
    //    }
    //    html.renderIntoDOM(document.getElementById("example"))
    val mountNode = document.getElementById("example")
    val HelloMessage = ScalaComponent.builder[String]
      .render($ => div("Hello ", $.props))
      .build

    HelloMessage("John").renderIntoDOM(mountNode)
  }

  def getId = {
    g.id.toString
  }

  @JSExport("viewShow")
  def viewShow(id: String) = {
    val url = g.jsRoutes.controllers.DataController.getFileDataById().url.toString
    println(id)
    Ajax.get(url = s"${url.noCache}&id=${id}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val dict = xhr.responseText.toJDJAn
      dict.foreach { case (k, v) =>
        val trueV = k match {
          case "size" => span(Tool.getFileSize(v))
          case "fileName" => span(v.toString)
          case "tags" => span(Tool.tagMap(v.toString))
          case _ => span(v.toString)
        }
        if ($(s"#fileInfo #${k}").length > 0) {
          trueV.renderIntoDOM($(s"#fileInfo #${k}")(0))
        }
      }
      refreshData(dict("id").toString, dict("fileName").toString)
    }
  }

  def refreshData(id: String, fileName: String) = {
    val index = layer.alert(Tool.loadingElement, Tool.layerOptions)
    val url = g.jsRoutes.controllers.DataController.getFileData().url.toString
    Ajax.get(url = s"${url.noCache}&id=${id}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJDJAn
      val columnNames = rs("columnNames").asInstanceOf[js.Array[String]]
      val columns = columnNames.map { columnName =>
        val fmt = columnName
        ColumnOptions.field(columnName).title(columnName).sortable(true)
      }
      val exportOptions = ExportOptions.fileName(fileName).csvSeparator("\t").csvEnclosure("")
      val options = TableOptions.data(rs("array")).columns(columns).search(true).pagination(true).exportOptions(exportOptions).
        showExport(true).exportDataType("all").exportTypes(js.Array("txt")).locale(Tool.getBTLanguage)
      $(s"#${tableId}").bootstrapTable(options)
      layer.close(index)
    }
  }

}
